package com.lyz.moil.web.action;

import com.lyz.moil.core.orm.PageData;
import com.lyz.moil.core.utils.WebUtils;
import com.lyz.moil.web.entity.DeviceApp;
import com.lyz.moil.web.service.DeviceAppService;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/moil/deviceApp")
public class DeviceAppAction {
    @Resource
    private DeviceAppService deviceAppService;

    @RequestMapping("/list")
    public ModelMap list(HttpServletRequest request) {
        PageData<DeviceApp> pageData = new PageData<DeviceApp>();
        // 给pageData设置参数
        WebUtils.setPageDataParameter(request, pageData);
        pageData = deviceAppService.find(pageData);

        return new ModelMap(pageData);
    }

    @RequestMapping(value = "/new")
    public String addForm(Model model) {
        return "/moil/deviceApp/input";
    }

    @RequestMapping(value = "/edit/{id}")
    public String editForm(@PathVariable("id") Integer id, Model model) {
        DeviceApp deviceApp = deviceAppService.find(id);
        model.addAttribute(deviceApp);
        return "/moil/deviceApp/input";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(DeviceApp deviceApp, HttpServletRequest request) {
        if (deviceApp.isNew()) {
            deviceAppService.save(deviceApp);
        } else {
            deviceAppService.update(deviceApp);
        }
        return "redirect:/moil/deviceApp/list";// 重定向
    }

    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        deviceAppService.delete(id);
        return "redirect:/moil/deviceApp/list";// 重定向
    }

    @RequestMapping(value = "/visible/{id}")
    public String visible(@PathVariable("id") Integer id) {
        deviceAppService.visible(id);
        return "redirect:/moil/deviceApp/list";// 重定向
    }

    @RequestMapping(value = "/unVisible/{id}")
    public String unVisible(@PathVariable("id") Integer id) {
        deviceAppService.unVisible(id);
        return "redirect:/moil/deviceApp/list";// 重定向
    }

    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
    }

}
